package space.sakana.edusysback.service;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import space.sakana.edusysback.entity.Admin;
import space.sakana.edusysback.entity.User;
import space.sakana.edusysback.mapper.AdminMapper;
import space.sakana.edusysback.mapper.UserMapper;
import space.sakana.edusysback.result.Result;
import space.sakana.edusysback.util.LoginUtil;
import space.sakana.edusysback.util.StringUtil;

@Service
public class LoginService {

    private UserMapper userMapper;
    private AdminMapper adminMapper;

    @Autowired
    public void autowiredMapper(UserMapper userMapper, AdminMapper adminMapper){
        this.userMapper = userMapper;
        this.adminMapper = adminMapper;
    }

    public Result userLogin(long code, String password, HttpServletRequest request, HttpServletResponse response) {
        User user = userMapper.selectUserByCode(code);
        if (user==null){
            return Result.failResult;
        }
        if (user.getPassword().equals(password)){
            String token = StringUtil.getRandomString();
            user.setToken(token);
            userMapper.updateUser(user);
            LoginUtil.setLoginToken(response, token);
            return Result.successResult;
        }
        return Result.failResult;
    }

    public Result adminLogin(String username, String password, HttpServletRequest request, HttpServletResponse response) {
        Admin admin = adminMapper.selectAdminByUsername(username);
        if (admin==null){
            return Result.failResult;
        }
        if (admin.getPassword().equals(password)){
            String token = StringUtil.getRandomString();
            admin.setToken(token);
            adminMapper.updateAdmin(admin);
            LoginUtil.setLoginToken(response, token);
            return Result.successResult;
        }
        return Result.failResult;
    }
}
